package com.d3works.apps.hr.service.project;

import com.d3works.apps.hr.db.TimesheetLine;
import com.d3works.apps.hr.db.repo.TimesheetLineRepository;
import com.d3works.apps.hr.service.timesheet.TimesheetLineService;
import com.d3works.apps.project.db.Project;
import com.d3works.apps.project.service.ProjectDashboardServiceImpl;
import com.d3works.apps.project.service.ProjectService;
import com.d3works.exception.D3worksException;
import com.google.inject.Inject;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

public class ProjectDashboardHRServiceImpl extends ProjectDashboardServiceImpl {

  @Inject TimesheetLineRepository timsheetLineRepo;
  @Inject TimesheetLineService timesheetLineService;
  @Inject ProjectService projectService;

  @Override
  public Map<String, Object> getData(Project project) {
    Map<String, Object> dataMap = super.getData(project);
    dataMap.put("$spentTime", getSpentTime(project));
    dataMap.put("$isShowTimeSpent", project.getIsShowTimeSpent());
    return dataMap;
  }

  protected BigDecimal getSpentTime(Project project) {
    List<TimesheetLine> timesheetLineList =
        timsheetLineRepo
            .all()
            .filter("self.project.id IN ?1", projectService.getContextProjectIds())
            .fetch();
    BigDecimal totalDuration = BigDecimal.ZERO;
    for (TimesheetLine timesheetLine : timesheetLineList) {
      try {
        totalDuration =
            totalDuration.add(
                timesheetLineService.computeHoursDuration(
                    timesheetLine.getTimesheet(), timesheetLine.getDuration(), true));
      } catch (D3worksException e) {
      }
    }
    return totalDuration;
  }
}
